package main

import (
	"context"
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	jaegercfg "github.com/uber/jaeger-client-go/config"
	"google.golang.org/grpc"
	"net"
	"oldpackagetest/gin_jaeger_test/gin/otgrpc"
	"oldpackagetest/gin_jaeger_test/gin/proto"
	"time"
)

type Server struct{}

func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {
	parentSpan := opentracing.SpanFromContext(ctx)

	one := opentracing.GlobalTracer().StartSpan("one", opentracing.ChildOf(parentSpan.Context()))
	time.Sleep(time.Second * 2) //业务逻辑
	one.Finish()

	two := opentracing.GlobalTracer().StartSpan("two", opentracing.ChildOf(parentSpan.Context()))
	time.Sleep(time.Second * 2) //业务逻辑
	two.Finish()

	three := opentracing.GlobalTracer().StartSpan("three", opentracing.ChildOf(parentSpan.Context()))
	time.Sleep(time.Second * 2) //业务逻辑
	three.Finish()

	four := opentracing.GlobalTracer().StartSpan("four", opentracing.ChildOf(parentSpan.Context()))
	time.Sleep(time.Second * 2) //业务逻辑
	four.Finish()

	return &proto.HelloReply{
		Message: "hello" + request.Name,
	}, nil
}
func main() {
	cfg := jaegercfg.Configuration{
		Sampler: &jaegercfg.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1, //全部采样
		},
		Reporter: &jaegercfg.ReporterConfig{
			//当span发送到服务器时要不要打日志
			LogSpans:           true,
			LocalAgentHostPort: "192.168.10.130:6831",
		},
		ServiceName: "gin-grpc",
	}
	tracer, closer, err := cfg.NewTracer(jaegercfg.Logger(jaeger.StdLogger))
	if err != nil {
		panic(err)
	}
	//设置tracer全局 节省到处传递tracer的过程
	opentracing.SetGlobalTracer(tracer)
	defer closer.Close()
	//拦截器
	g := grpc.NewServer(grpc.UnaryInterceptor(otgrpc.OpenTracingServerInterceptor(opentracing.GlobalTracer())))
	proto.RegisterGreeterServer(g, &Server{})
	lis, err := net.Listen("tcp", "0.0.0.0:50052")
	if err != nil {
		panic("失败：" + err.Error())
	}
	err = g.Serve(lis)
	if err != nil {
		panic("失败：" + err.Error())
	}
}
